<?php

namespace pmvc\mvc\ioc;

use pmvc\ioc\xml\ParseContext;

use pmvc\ioc\xml\XmlObjectFactory;
use pmvc\ioc\xml\Extension;
use pmvc\ioc\PropertyDescriptor;
use pmvc\ioc\ObjectDescriptor;

use pmvc\util\XMLUtil;

use DOMElement;
use Exception;

/**
 * Extension for setting up view handler mappings.
 *
 */
class ViewHandlerMappingExtension
	implements Extension {

	/**
	 * {@inheritDoc}
	 */
	public function process(DOMElement $element, ParseContext $pc) {

		// get values
		$handlerClass 	= XMLUtil::getAttributeValue($element, "class");
		$handlerId 		= XMLUtil::getAttributeValue($element, "handler");
		$id				= XMLUtil::getAttributeValue($element, "id", uniqid('', true)."#".__CLASS__);
		$path			= XMLUtil::getAttributeValue($element, "path");

		// make sure we have required info
		if (!isset($handlerClass) && !isset($handlerId)) {
			throw Exception("class or handler is required for view handler mapping");
		}

		// get paths
		$paths = Array();
		foreach ($pc->getXPath()->query("/paths/path", $element) as $pathElement) {
			$paths []= trim($element->textContent);
		}
		if (isset($path)) {
			$paths []= trim($path);
		}

		// create handler
		if (isset($handlerClass)) {
			$handlerId 		= uniqid('', true)."#".$handlerClass;
			$handlerDesc 	= new ObjectDescriptor($handlerId, $handlerClass);
			$pc->getObjectFactory()->addObjectDescriptor($handlerDesc);
		} 

		// create descriptor
		$mappingDesc = new ObjectDescriptor($id, 'pmvc\mvc\view\RegexViewHandlerMapping');

		// add mappings
		$mapProperties = Array();
		foreach ($paths as $path) {
			$mapProperties []= new PropertyDescriptor($path, $handlerId, PropertyDescriptor::TYPE_REF);
		}
		$mappingDesc->properties []= new PropertyDescriptor("regexMap", $mapProperties, PropertyDescriptor::TYPE_ARRAY);

		// add it
		$pc->getObjectFactory()->addObjectDescriptor($mappingDesc);
	}
}
?>